<?php

/**
 * Library :: DAL (Data Access Layer) :: DataObjectRow
 *
 * Warlock is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 *
 * @package    warlock
 * @author     David Cole <neophyte@sourcetutor.com>
 * @license    GNU/GPL v2
 */

class DAL_DataObjectRow
{
    /**
     * Data Object
     *
     * The data object to which this row
     * relates.
     *
     * @var string
     * @access private
     */
    var $_DataObject;

    /**
     * Data Access Layer
     *
     * @var DAL
     * @access private
     */
    var $_DAL;

    /**
     * Field Name
     *
     * An aray holding all the field names
     * accessible to the Data Object Row.
     *
     * @var array
     * @access private
     */
    var $_Fields = array();

    var $_OriginalData;
    
    /**
     * Constructor
     *
     * General initialisation including setting
     * the object properties with the field => value
     * pairs of the Data Object
     *
     * @param string $do    Data Object to which the row relates
     * @param array  $data  An associative array of the field => value pairs
     *
     * @return DAL_DataObjectRow
     */
    function DAL_DataObjectRow($do, $data)
    {
        $this->_DAL          = &Vault::Get('DAL');
        $this->_DataObject   = $do;
        $this->_Fields       = array_keys($data);
        $this->_OriginalData = $data;
        
        foreach ($data as $field => $value)
            $this->{$field} = $value;
    }

    /**
     * Save Record
     *
     * Attempts to save the current record, for this to work
     * the table needs to have a primary key.
     *
     * @return int Number of affected rows, generally 1 on success and false on failure
     * @access public
     */
    function Save()
    {
        $update = array();
        
        for ($i = 0; $i < count($this->_Fields); $i++)
            if ($this->{$this->_Fields[$i]} != $this->_OriginalData[$this->_Fields[$i]])
                $update[$this->_Fields[$i]] = $this->{$this->_Fields[$i]};

        return $this->_DAL->Update($this->_DataObject, $update, $this->{$this->_DAL->DataObjects[$this->_DataObject]->PrimaryKey});
    }

    /**
     * Delete Record
     *
     * Attempts to delete the current record, for this to work
     * the table needs to have a primary key.
     *
     * @return int Number of affected rows, generally 1 on success and false on failure
     * @access public
     */
    function Delete()
    {
        return $this->_DAL->Delete($this->_DataObject, $this->{$this->_DAL->DataObjects[$this->_DataObject]->PrimaryKey});
    }
}

?>